﻿/*
Copyright (c) 2008 William Duff

Permission is hereby granted, free of charge, to any person obtaining a copy 
of this software and associated documentation files (the "Software"), to deal 
in the Software without restriction, including without limitation the rights 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all 
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 
SOFTWARE.
*/

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using LiveUpload.Facebook.Properties;

namespace LiveUpload.Facebook
{
    /// <summary>
    /// This class encapsulates a lot of the data involved in the upload process. Once all of its
    /// properties are set correctly, all that is needed is to run the UploadChunk method until the
    /// upload is completed.
    /// </summary>
    public class UploadContext
    {
        #region Constructors

        /// <summary>
        /// Constructs a new UploadContext object to facilitate uploading an item.
        /// </summary>
        public UploadContext(string url)
        {
            this.request = (HttpWebRequest)WebRequest.Create(url);
            this.request.Method = "POST";
            this.request.Timeout = System.Threading.Timeout.Infinite;
        }

        #endregion

        #region Private Fields

        private HttpWebRequest request;
        private byte[] header;
        private Stream dataStream;
        private byte[] footer;
        private Stream requestStream;
        private long currentPosition;
        private int chunkSize;

        #endregion

        #region Public Fields

        /// <summary>
        /// A HTTP request used to initiate the upload.
        /// </summary>
        public HttpWebRequest Request
        {
            get { return this.request; }
            set { this.request = value; }
        }

        /// <summary>
        /// The header for the POST upload request. Should be UTF-8 encoded.
        /// </summary>
        public byte[] Header
        {
            get { return this.header; }
            set { this.header = value; }
        }

        /// <summary>
        /// Used to transmit file data during the POST upload request.
        /// </summary>
        public Stream DataStream
        {
            get { return this.dataStream; }
            set { this.dataStream = value; }
        }
        /// <summary>
        /// The footer for the POST upload request. Should be UTF-8 encoded.
        /// </summary>
        public byte[] Footer
        {
            get { return this.footer; }
            set { this.footer = value; }
        }
        /// <summary>
        /// A stream used to write the POST upload request.
        /// </summary>
        public Stream RequestStream
        {
            get { return this.requestStream; }
            set { this.requestStream = value; }
        }

        /// <summary>
        /// How many bytes we've written to the request stream. The 'Position' member is not 
        /// supported by WebResponse, so this will have to do.
        /// </summary>
        public long CurrentPosition
        {
            get { return this.currentPosition; }
        }

        /// <summary>
        /// We chunk the upload into pieces for memory and UI reasons.
        /// </summary>
        public int ChunkSize
        {
            get { return this.chunkSize; }
            set { this.chunkSize = value; }
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Upload one chunk of a file. This is to make sure that only a small piece of a (possibly 
        /// huge) file is read from disk into memory at a time. Intended to be called repeatedly 
        /// until it returns false.
        /// </summary>
        /// <returns>
        /// true to continue uploading, false if upload is complete.
        /// </returns>
        public bool UploadChunk()
        {
            if (this.currentPosition < this.header.LongLength)
            {
                // Upload either an entire chunk, or however much remains in the head buffer.
                int chunk = Math.Min(this.chunkSize,
                    (int)(this.header.LongLength - this.currentPosition));

                // Offset into head buffer. Throws an exception if larger than an int!
                int offset = Convert.ToInt32(this.currentPosition);

                this.requestStream.Write(this.header, (int)this.currentPosition, chunk);
                this.currentPosition += chunk;
            }
            else if (this.currentPosition < this.header.LongLength + this.dataStream.Length)
            {
                // Upload either an entire chunk, or however much remains in the data stream.
                int chunk = Math.Min(this.chunkSize,
                    (int)(this.header.LongLength + this.dataStream.Length - this.currentPosition));

                // Safely read from the data stream.
                byte[] dataBuffer = new byte[chunk]; // Buffer to store a chunk of data.
                int offset = 0; // Offset into buffer.
                int toRead = chunk; // The amount to read from the data stream.
                while (toRead > 0)
                {
                    int read = this.dataStream.Read(dataBuffer, offset, toRead);
                    if (read <= 0)
                    {
                        throw new EndOfStreamException(String.Format(
                            "End of file reached with {0} bytes left to read", toRead));
                    }
                    toRead -= read;
                    offset += read;
                }

                // Write however much we read from the data stream.
                this.requestStream.Write(dataBuffer, 0, chunk);
                this.currentPosition += chunk;
            }
            else
            {
                // Upload either an entire chunk, or however much remains in the foot buffer.
                int chunk = Math.Min(this.chunkSize,
                    (int)(this.header.LongLength + this.dataStream.Length + this.footer.LongLength -
                    this.currentPosition));

                // Offset into foot buffer. Throws an exception if larger than an int!
                int offset = Convert.ToInt32(this.currentPosition - this.header.LongLength -
                    this.dataStream.Length);

                this.requestStream.Write(this.footer, offset, chunk);
                this.currentPosition += chunk;
            }

            return this.currentPosition < (this.header.LongLength + this.dataStream.Length + this.footer.LongLength);
        }

        /// <summary>
        /// Our IPublishProgressCallback callback. Each time we upload a chunk, this function
        /// is called to update the UI on how far the download has progressed.
        /// </summary>
        public int PercentComplete
        {
            get
            {
                return Convert.ToInt32((this.currentPosition * 100) /
                    (this.header.LongLength + this.dataStream.Length + this.footer.LongLength));
            }
        }

        #endregion
    }
}
